<template>
  <div>
    <h3>工具信息管理</h3>
    <div v-if="editorVisble">
      <el-button type="primary" @click="add">添加工具</el-button>
      <el-button type="primary" @click="upload">上 传</el-button>
      <el-button type="primary" @click="download">下载所有数据</el-button>
    </div>
    <el-form inline :model="search" style="margin-top: 20px">
      <el-form-item label="根据工具编号搜索">
        <el-input
          v-model="search.bardoce"
          placeholder="请输入工具编号"
          @keyup.enter.native="searchList"
        ></el-input>
      </el-form-item>
      <el-form-item label="根据工具名称搜索">
        <el-input v-model="search.name" placeholder="请输入工具名称"></el-input>
      </el-form-item>
      <el-form-item label="根据工具件号搜索">
        <el-input
          v-model="search.partNo"
          placeholder="请输入工具件号"
        ></el-input>
      </el-form-item>
      <el-form-item label="工具类型">
        <el-select v-model="search.consumeFlag" placeholder="请输入工具类型">
          <el-option
            v-for="item in toolType"
            :label="item.type"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="searchList">查 询</el-button>
    </el-form>
    <!-- <el-switch
      v-model="switch_type"
      active-text="所有工具"
      inactive-text="计量工具"
    >
    </el-switch> -->
    <el-table :data="tableData" :row-class-name="rowClassName">
      <el-table-column label="工具名称" prop="name"></el-table-column>
      <el-table-column label="工具编号" prop="barcode"></el-table-column>
      <el-table-column label="工具件号" prop="partNo"></el-table-column>
      <el-table-column label="工具序号" prop="serialNo"></el-table-column>
      <el-table-column label="存放地点" prop="storage"></el-table-column>
      <el-table-column label="工具总数" prop="allNumber"></el-table-column>
      <el-table-column label="库内数量" prop="userableNum"></el-table-column>
      <el-table-column label="工具类型" prop="consumeFlag">
        <template slot-scope="scope">
          <span v-for="tool in toolType" :key="tool.id">
            <span v-if="scope.row.consumeFlag === tool.value">
              {{ tool.type }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="detail(scope.row)" type="text" size="small"
            >查看</el-button
          >
          <el-button
            @click="edit(scope.row)"
            type="text"
            size="small"
            v-if="editorVisble"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="deleteHandler(scope.row)"
            size="small"
            v-if="editorVisble"
            >删除</el-button
          >
          <el-button type="text" @click="imageHandler(scope.row)" size="small"
            >图片</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <el-dialog
      :title="isDisabled ? '查看工具' : '添加/修改工具'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="formInline" :rules="inlineRules" ref="formInline">
        <el-form-item label="工具编号" prop="barcode">
          <el-input
            v-model="formInline.barcode"
            placeholder="请输入工具编号"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="件号" prop="partNo">
          <el-input
            v-model="formInline.partNo"
            placeholder="请输入件号"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="序号" prop="serialNo">
          <el-input
            v-model="formInline.serialNo"
            placeholder="请输入序号"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="工具名称" prop="name">
          <el-input
            v-model="formInline.name"
            placeholder="请输入工具名称"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="存放地点" prop="storage">
          <el-input
            v-model="formInline.storage"
            placeholder="请输入存放地点"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="厂家" prop="vender">
          <el-input
            v-model="formInline.vender"
            placeholder="请输入厂家"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格（人民币）" prop="price">
          <el-input
            v-model="formInline.price"
            placeholder="请输入价格"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formInline.remark"
            placeholder="请输入备注"
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="工具状态" prop="status">
          <el-select
            v-model="formInline.status"
            placeholder="请输入工具状态"
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in toolStatus"
              :label="item.discription"
              :value="item.status"
              :key="item.status"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="consumeFlag">
          <el-select
            v-model="formInline.consumeFlag"
            placeholder="请选择类型"
            :disabled="isDisabled"
          >
            <el-option
              v-for="item in toolType"
              :label="item.type"
              :value="item.value"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工具总数" prop="allNumber">
          <el-input-number
            v-model="formInline.allNumber"
            placeholder="请选择数量 "
            :disabled="isDisabled"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="上次校验日期"
          prop="lastInspDate"
          v-if="formInline.consumeFlag == 1"
        >
          <el-date-picker
            type="date"
            v-model="formInline.lastInspDate"
            placeholder="请选择上次校验日期"
            :disabled="isDisabled"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="校验到期日期"
          prop="expireDate"
          v-if="formInline.consumeFlag == 1"
        >
          <el-date-picker
            type="date"
            v-model="formInline.expireDate"
            placeholder="请选择校验到期日期"
            :disabled="isDisabled"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="工具校验证书"
          prop="certificate"
          v-if="formInline.consumeFlag == 1"
        >
          <el-input
            v-model="formInline.certificate"
            placeholder="请输入工具校验证书 "
            :disabled="isDisabled"
          ></el-input>
        </el-form-item>
      </el-form>
      <div v-show="!isDisabled">
        <el-button type="primary" @click="reset('formInline')">重 置</el-button>
        <el-button type="primary" @click="confirm('formInline')"
          >提 交</el-button
        >
      </div>
    </el-dialog>
    <el-dialog title="上传工具清单" :visible.sync="uploadDialog">
      <el-upload
        :action="actionUrl"
        drag
        :headers="customHeaders"
        :on-success="handleExcelSuccess"
        :on-error="handleExcelError"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-dialog>
    <el-dialog :title="toolName" :visible.sync="imageUploadVisable">
      <!-- 这里如果该工具有图片就显示图片，没有图片就显示上传界面 -->
      <el-upload
        :action="uploadImageUrl"
        drag
        :headers="customHeaders"
        :on-success="handleImageSuccess"
        :on-error="handleImageError"
        v-if="!imageShow && editorVisble"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
      <div v-if="imageShow">
        <el-image :src="src" @click="changeImage"></el-image>
        <el-button v-if="editorVisble" type="danger" @click="deleteImage"
          >删除图片</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import toolApi from "@/api/tool/index";
import toolTypeApi from "@/api/toolType/index";
import store from "@/store";
import { getToken } from "@/utils/auth";
import dateUtils from "@/utils/dateUtils";
import { verifyBarcode } from "@/utils/verify/verify";
import host from "@/utils/host";

const url = `http://${host}:8081`;
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    const validateBarcode = (rule, value, callback) => {
      // 使用正则表达式进行匹配
      // 匹配数字开头，后面跟着九个数字，且开头不为0
      const regex = /^[1-9]\d{8}$/;
      if (!regex.test(value)) {
        callback(new Error("工具编号必须是九位正整数！"));
      } else {
        callback();
      }
    };
    const validatePrice = (rule, value, callback) => {
      // 使用正则表达式进行匹配
      // 匹配数字开头，后面跟着九个数字，且开头不为0
      if (isNaN(value)) {
        callback(new Error("价格只能是数字"));
      } else {
        callback();
      }
    };
    const validateNum = (rule, value, callback) => {
      // 使用正则表达式进行匹配
      // 匹配数字开头，后面跟着九个数字，且开头不为0
      if (
        this.formInline.consumeFlag != 3 &&
        this.formInline.consumeFlag != 4 &&
        value > 1
      ) {
        callback(new Error("常用工具或计量工具数量不得大于1！"));
      } else if (value < 1) {
        callback(new Error("工具数量不能小于1"));
      } else {
        callback();
      }
    };
    const validateLast = (rule, value, callback) => {
      const expireDate = new Date(this.formInline.expireDate);
      const lastDate = new Date(value);
      if (this.formInline.consumeFlag == 1) {
        if (lastDate.getTime() > expireDate.getTime()) {
          callback(new Error("上次校验日期不能在工具过期日期的后面！"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateExpire = (rule, value, callback) => {
      if (this.formInline.consumeFlag == 1) {
        const lastDate = new Date(this.formInline.lastInspDate);
        const expireDate = new Date(value);
        if (value == undefined) {
          callback(new Error("校验到期日期不能为空！"));
        } else if (lastDate.getTime() > expireDate.getTime()) {
          callback(new Error("上次校验日期不能在工具过期日期的后面！"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateCati = (rule, value, callback) => {
      if (this.formInline.consumeFlag == 1) {
        if (value == undefined) {
          callback(new Error("工具校验证书不能为空！"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateStatus = (rule, value, callback) => {
      if (value !== "") {
        if (!this.editFlag) {
          //当进行添加时，该状态必须是正常
          if (value != 0) {
            callback(new Error("添加时工具状态必须是正常！"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback(new Error("工具状态不能为空！"));
      }
    };
    //这里存放数据
    return {
      actionUrl: `http://${host}:8081/T01/tool/upload`,
      toolName: "", //上传图片时用于显示工具名称
      toolId: "", //更改图片时用于选择工具id
      imageShow: false, //控制图片显示还是上传界面显示
      src: "", //点击工具图片用于显示的工具的图片的src地址
      uploadImageUrl: "", //上传图片时的url地址
      toolStatus: [
        //工具状态的类型，用于列表渲染
        { status: 0, discription: "正常" },
        { status: 1, discription: "隔离" },
        { status: 2, discription: "报废" },
      ],
      //用于在请求头中携带token
      customHeaders: {
        Authorization: getToken(),
      },
      uploadDialog: false, //上传工具清单的对话框
      editorVisble: false, //如果是管理员登录，则显示这些功能，如果不是，则不显示
      tempTableData: [], //切换工具类型从全部工具到计量工具时的临时列表数据
      // switch_type: true, //用于切换是全部工具还是计量工具，true表示全部工具
      search: {
        bardoce: "",
        name: "",
        partNo: "",
        consumeFlag: "",
      },
      isDisabled: false, //当进行查看工具时，禁用修改表单的数据，此时为true，当添加或修改工具信息时，可以修改表单数据，此时为false
      toolType: [],
      formInline: {
        id: "",
        barcode: "",
        partNo: "",
        serialNo: "",
        name: "",
        modelNo: "",
        storage: "",
        vender: "",
        price: "",
        createBy: "",
        createTime: "",
        editBy: "",
        editTime: "",
        remark: "",
        status: "",
        consumeFlag: "",
        allNumber: "",
        lastInspDate: "",
        expireDate: "",
        certificate: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      editFlag: false, //当进行编辑时，该标记为true，当进行添加时，该标记为false
      dialogFormVisible: false, //工具信息的对话框
      imageUploadVisable: false, //图片信息的对话框
      inlineRules: {
        barcode: [
          { required: true, trigger: "blur", validator: validateBarcode },
        ],
        partNo: [
          { required: false, trigger: "blur", message: "件号不能为空！" },
        ],
        serialNo: [
          {
            required: false,
          },
        ],
        name: [
          { required: true, trigger: "blur", message: "工具名称不能为空！" },
        ],
        storage: [
          { required: true, trigger: "blur", message: "存放地点不能为空！" },
        ],
        vender: [
          {
            required: false,
          },
        ],
        price: [{ required: false, trigger: "blur", validator: validatePrice }],
        remark: [
          {
            required: false,
          },
        ],
        status: [
          {
            required: true,
            trigger: "blur",
            validator: validateStatus,
          },
        ],
        consumeFlag: [
          { required: true, trigger: "blur", message: "工具类型不能为空！" },
        ],
        allNumber: [
          { required: true, trigger: "blur", validator: validateNum },
        ],
        lastInspDate: [
          {
            required: false,
            trigger: "blur",
            validator: validateLast,
          },
        ],

        expireDate: [
          { required: true, trigger: "blur", validator: validateExpire },
        ],
        certificate: [
          {
            required: true,
            trigger: "blur",
            validator: validateCati,
          },
        ],
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {
    // switch_type(newVal, oldVal) {
    //   if (newVal) {
    //     this.tableData = this.tempTableData;
    //   } else {
    //     const filteredArray = this.tableData.filter((item) => {
    //       return item.consumeFlag == 1;
    //     });
    //     this.tempTableData = this.tableData;
    //     this.tableData = filteredArray;
    //   }
    // },
    //监视工具编号的位数，当其等于9位数字时自动触发查询事件
    // search: {
    //   handler(newVal, oldVal) {
    //     if (newVal.bardoce.length == 9) {
    //       this.searchList();
    //       if (this.tableData.length != 0) {
    //         this.search.bardoce = "";
    //       }
    //     }
    //   },
    //   deep: true,
    // },
  },
  //方法集合
  methods: {
    /**
     * 删除图片
     */
    deleteImage() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          toolApi.deleteImage(this.toolId);
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.imageShow = false;
          this.refreshList(1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * 修改图片
     */
    changeImage() {
      console.log(this.editorVisble);
      if (this.editorVisble) {
        this.uploadImageUrl = `//${host}:8081/T01/tool/image/${this.toolId}`;
        this.imageShow = false;
      }
    },
    /**
     * 点击图片按钮，此时根据该工具是否有图片会出现上传图片对话框还是显示图片
     */
    imageHandler(data) {
      this.imageUploadVisable = true;
      this.toolName = data.name;
      this.toolId = data.id;
      if (!data.imageSrc) {
        this.uploadImageUrl = `//${host}:8081/T01/tool/image/${data.id}`;
        this.imageShow = false;
      } else {
        this.src = url + data.imageSrc;
        this.imageShow = true;
      }
    },
    /**
     * 图片上传成功后的回调
     */
    handleImageSuccess(response) {
      if (response.code == 20000) {
        this.$message({
          message: "上传成功！",
          type: "success",
        });
        this.src = url + response.message;
        this.imageShow = true;
        this.refreshList(1);
      } else {
        this.$message({
          message: `${response.message}`,
          type: "error",
        });
      }
    },
    /**
     * 图片上传失败后的回调
     */
    handleImageError(error) {
      this.$message({
        message: `${error.message || error.data}`,
        type: "error",
      });
    },
    /**
     * 工具清单上传成功后的回调
     */
    handleExcelSuccess(data) {
      if (data.code == 20000) {
        this.$message({
          message: "上传成功！",
          type: "success",
        });
        this.uploadDialog = false;
        this.refreshList(1);
      } else {
        this.$message({
          message: `${data.message}`,
          type: "error",
        });
      }
    },
    handleExcelError(error) {
      this.$message({
        message: `${error.message || error.data}`,
        type: "error",
      });
    },
    /**
     * 自定义表单行的样式
     */
    rowClassName({ row }) {
      if (row.status == 0) {
        if (row.consumeFlag == 1) {
          if (dateUtils.dateCompare(row.expireDate) == 1) {
            return "warning-row"; // 返回自定义的类名
          } else if (dateUtils.dateCompare(row.expireDate) == 2) {
            return "caution-row"; //返回自定义的类名
          } else {
            return ""; // 返回空字符串
          }
        }
      } else {
        return "unUseable-row";
      }
    },
    download() {
      toolApi.download();
    },
    upload() {
      this.uploadDialog = true;
    },
    searchList() {
      this.getTotal();
      this.list(1);
    },
    detail(data) {
      this.formInline = { ...data };
      this.dialogFormVisible = true;
      this.isDisabled = true;
    },
    resetForm() {
      this.formInline = {
        id: "",
        barcode: "",
        partNo: "",
        serialNo: "",
        name: "",
        modelNo: "",
        storage: "",
        status: "",
        vender: "",
        price: "",
        createBy: "",
        createTime: "",
        editBy: "",
        editTime: "",
        remark: "",
        consumeFlag: "",
        allNumber: "",
      };
    },
    confirm(formInline) {
      this.$refs[formInline].validate((valid) => {
        if (valid) {
          if (!this.editFlag) {
            //进行添加操作
            toolApi.add(this.formInline).then((res) => {
              this.$message({
                message: "添加成功！",
                type: "success",
              });
            });
          } else {
            //进行更新操作
            toolApi.update(this.formInline).then((res) => {
              this.$message({
                message: "更新成功！",
                type: "success",
              });
            });
          }
          this.resetForm();
          this.dialogFormVisible = false;
          this.refreshList(this.currentPage);
        } else {
          console.log("error submit!!");
        }
      });
    },
    reset(formInline) {
      this.$refs[formInline].resetFields();
    },
    edit: async function (data) {
      this.dialogFormVisible = true;
      this.editFlag = true;
      this.isDisabled = false;
      this.formInline = { ...data };
    },
    add() {
      this.resetForm();
      this.editFlag = false;
      this.dialogFormVisible = true;
      this.isDisabled = false;
    },
    deleteHandler(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          toolApi.delete(data.id).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.refreshList(this.currentPage);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange: async function (currentPage) {
      // this.switch_type = true;
      this.list(currentPage);
    },
    list: async function (currentPage) {
      if (verifyBarcode(this.search.bardoce, this)) {
        const res = await toolApi.list(
          currentPage,
          this.pageSize,
          this.search.bardoce,
          this.search.name,
          this.search.partNo,
          this.search.consumeFlag
        );
        this.tableData = res.data;
        this.currentPage = currentPage;
      }
    },
    getTotal: async function () {
      if (verifyBarcode(this.search.bardoce, this)) {
        const res = await toolApi.total(
          this.search.bardoce,
          this.search.name,
          this.search.partNo,
          this.search.consumeFlag
        );
        this.total = res.data;
      }
    },
    refreshList: async function (currentPage) {
      await this.getTotal();
      this.list(currentPage);
    },
    //获取工具类型
    getToolType: async function () {
      const res = await toolTypeApi.getAll();
      this.toolType = res.data;
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.refreshList(1);
    this.getToolType();
    if (store.getters.roles.includes("admin")) {
      this.editorVisble = true;
    } else {
      this.editorVisble = false;
    }
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style>
.el-table .warning-row {
  color: red;
}

.el-table .caution-row {
  color: rgb(255, 123, 0);
}

.el-table .unUseable-row {
  background-color: pink;
}
</style>
